package com.industrial.premu.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.industrial.common.core.utils.uuid.UUID;
import com.industrial.common.core.web.domain.AjaxResult;
import com.industrial.common.security.utils.SecurityUtils;
import com.industrial.premu.domain.PreMuCompanyInfo;
import com.industrial.premu.domain.PreMuEvaluationDataSubmission;
import com.industrial.premu.domain.sqsj.*;
import com.industrial.premu.dto.PreMuEvaluationDataSubmissionDto;
import com.industrial.premu.mapper.PreMuEvaluationDataSubmissionMapper;
import com.industrial.premu.mapper.SysAreaMapper;
import com.industrial.premu.mapper.SysDictDataMapper;
import com.industrial.premu.mapper.SysUserMapper;
import com.industrial.premu.service.*;
import com.industrial.premu.util.PageResult;
import com.industrial.premu.util.PageUtils;
import com.industrial.premu.vo.PreMuEvaluationDataSubmissionVo;
import com.industrial.system.api.domain.SysUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PreMuEvaluationDataSubmissionServiceImpl implements IPreMuEvaluationDataSubmissionService {

    @Autowired
    private PreMuEvaluationDataSubmissionMapper preMuEvaluationDataSubmissionMapper;

    @Autowired
    private IPreMuCompanyInfoService preMuCompanyInfoService;

    @Autowired
    private SysAreaMapper sysAreaMapper;

    @Autowired
    private IPreMuImportShuiwuService preMuImportShuiwuService;

    @Autowired
    private IPreMuImportTongjiService  preMuImportTongjiService;

    @Autowired
    private IPreMuImportHuanbaoService preMuImportHuanbaoService;

    @Autowired
    private IPreMuImportRensheService preMuImportRensheService;

    @Autowired
    private IPreMuImportLogService preMuImportLogService;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysDictDataMapper sysDictDataMapper;

    @Override
    public AjaxResult submitData(PreMuEvaluationDataSubmissionDto dto) {
        String userId = SecurityUtils.getUserId();
        List<PreMuEvaluationDataSubmission> list = preMuEvaluationDataSubmissionMapper.selectSubmissionByUsccAndYear(dto.getUscc(), dto.getYear());
        if (list.size() > 0) {
            return AjaxResult.warn("该企业该年度数据已提报，请勿重复提交");
        }
        PreMuEvaluationDataSubmission dataSubmission = new PreMuEvaluationDataSubmission();
        BeanUtils.copyProperties(dto, dataSubmission);
        dataSubmission.setId(UUID.randomUUID().toString());
        dataSubmission.setCreateBy(userId);
        dataSubmission.setCreateDate(new Date());
        dataSubmission.setUpdateBy(userId);
        dataSubmission.setUpdateDate(new Date());
        PreMuCompanyInfo preMuCompanyInfo = preMuCompanyInfoService.selectPreMuCompanyInfoByUscc(dto.getUscc());
        dataSubmission.setProvince(preMuCompanyInfo.getProvince());
        dataSubmission.setCity(preMuCompanyInfo.getCity());
        dataSubmission.setCounty(preMuCompanyInfo.getCounty());
        this.saveData(dataSubmission);
        return AjaxResult.success("提报成功");
    }

    @Override
    public void saveData(PreMuEvaluationDataSubmission dataSubmission) {
        preMuEvaluationDataSubmissionMapper.insertData(dataSubmission);
    }

    @Override
    public boolean getFlag() {
        SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
        String uscc = sysUser.getUserName();
        String year = String.valueOf(LocalDate.now().getYear() - 1);
        List<PreMuEvaluationDataSubmission> list = preMuEvaluationDataSubmissionMapper.selectSubmissionByUsccAndYear(uscc, year);
        if (list.size() > 0) {
            return false;
        } else {
            return true;
        }
    }

    @Override
    public Map<String, String> getCompanyInfo() {
        Map<String, String> map = new HashMap<>();
        SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
        if (sysUser != null) {
            map.put("companyName", sysUser.getNickName());
            String uscc = sysUser.getUserName();
            map.put("uscc", uscc);
            PreMuCompanyInfo preMuCompanyInfo = preMuCompanyInfoService.selectPreMuCompanyInfoByUscc(uscc);
            if (preMuCompanyInfo != null) {
                String companyType = preMuCompanyInfo.getCompanyType();
                map.put("companyType", companyType);
                map.put("companyTypeName", StrUtil.equals(companyType, "1") ? "规上企业" : "规下企业");
                String provinceName = sysAreaMapper.selectAreaNameByCode(preMuCompanyInfo.getProvince());
                map.put("provinceName", provinceName);
                String cityName = sysAreaMapper.selectAreaNameByCode(preMuCompanyInfo.getCity());
                map.put("cityName", cityName);
                String countyName = sysAreaMapper.selectAreaNameByCode(preMuCompanyInfo.getCounty());
                map.put("countyName", countyName);
                String industryType = preMuCompanyInfo.getIndustryType();
                map.put("industryType", industryType);
                String dictLabel = sysDictDataMapper.selectDictLabel("industry_names", industryType);
                map.put("industryTypeName", dictLabel);
            } else {
                map.put("companyType", "");
                map.put("companyTypeName", "");
                map.put("provinceName", "");
                map.put("cityName", "");
                map.put("countyName", "");
                map.put("industryType", "");
                map.put("industryTypeName", "");
            }
        } else {
            map.put("companyName", "");
            map.put("uscc", "");
            map.put("companyType", "");
            map.put("companyTypeName", "");
            map.put("provinceName", "");
            map.put("cityName", "");
            map.put("countyName", "");
            map.put("industryType", "");
            map.put("industryTypeName", "");
        }
        return map;
    }

    @Override
    public PageResult<PreMuEvaluationDataSubmissionVo> page(PreMuEvaluationDataSubmissionDto dto) {
        SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
        String uscc = sysUser.getUserName();
        dto.setUscc(uscc);
        List<PreMuEvaluationDataSubmissionVo> list = preMuEvaluationDataSubmissionMapper.selectList(dto);
        return PageUtils.paginateList(list, dto.getPageNum() != null ? dto.getPageNum() : 1, dto.getPageSize() != null ? dto.getPageSize() : 99);
    }

    @Override
    public PreMuEvaluationDataSubmissionVo getDataSubmissionById(String id) {
        return preMuEvaluationDataSubmissionMapper.selectDataSubmissionById(id);
    }

    @Override
    public AjaxResult resubmitData(PreMuEvaluationDataSubmissionDto dto) {
        String userId = SecurityUtils.getUserId();
        PreMuEvaluationDataSubmission dataSubmission = new PreMuEvaluationDataSubmission();
        BeanUtils.copyProperties(dto, dataSubmission);
        dataSubmission.setUpdateBy(userId);
        dataSubmission.setUpdateDate(new Date());
        dataSubmission.setStatus("0");
        this.updateDataById(dataSubmission);
        return AjaxResult.success("提报成功");
    }

    @Override
    public void updateDataById(PreMuEvaluationDataSubmission dataSubmission) {
        preMuEvaluationDataSubmissionMapper.updateDataById(dataSubmission);
    }

    @Override
    public PageResult<PreMuEvaluationDataSubmissionVo> pageBackend(PreMuEvaluationDataSubmissionDto dto) {
        List<PreMuEvaluationDataSubmissionVo> list = preMuEvaluationDataSubmissionMapper.selectList(dto);
        return PageUtils.paginateList(list, dto.getPageNum() != null ? dto.getPageNum() : 1, dto.getPageSize() != null ? dto.getPageSize() : 9999999);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult approvalDataBatch(PreMuEvaluationDataSubmissionDto dto) {
        String status = dto.getStatus();
        String userId = SecurityUtils.getUserId();
        if (StrUtil.equals(status, "1")) {
            // 通过
            List<String> idList = dto.getIdList();
            for (String id : idList) {
                // 将数据更新到相应表中尚未有值的记录中
                PreMuEvaluationDataSubmissionVo dataSubmission = this.getDataSubmissionById(id);
                String uscc = dataSubmission.getUscc();
                String year = dataSubmission.getYear();
                String submissionUpdateBy = dataSubmission.getUpdateBy();

                // 查询税务局导入数据是否存在当前年度的记录
                PreMuImportShuiwu preMuImportShuiwuCondition = new PreMuImportShuiwu();
                preMuImportShuiwuCondition.setUscc(uscc);
                preMuImportShuiwuCondition.setYear(year);
                List<PreMuImportShuiwu> preMuImportShuiwus = preMuImportShuiwuService.selectPreMuImportShuiwuList(preMuImportShuiwuCondition);
                if (preMuImportShuiwus != null && preMuImportShuiwus.size() == 0) {
                    // 插入一条新数据
                    PreMuImportShuiwu preMuImportShuiwu = new PreMuImportShuiwu();
                    preMuImportShuiwu.setId(IdUtil.simpleUUID());
                    preMuImportShuiwu.setYear(year);
                    preMuImportShuiwu.setUscc(uscc);
                    preMuImportShuiwu.setCompanyName(dataSubmission.getCompanyName());
                    preMuImportShuiwu.setMainIncome(dataSubmission.getMainIncome());
                    preMuImportShuiwu.setRdFunds(String.valueOf(dataSubmission.getRdFunds()));
                    preMuImportShuiwu.setCreateBy(submissionUpdateBy);
                    preMuImportShuiwu.setCreateDate(dataSubmission.getUpdateDate());
                    preMuImportShuiwu.setUpdateBy(submissionUpdateBy);
                    preMuImportShuiwu.setUpdateDate(dataSubmission.getUpdateDate());
                    preMuImportShuiwu.setProfitTotal(dataSubmission.getProfitTotal());
                    preMuImportShuiwuService.insertPreMuImportShuiwu(preMuImportShuiwu);
                }

                // 查询统计局导入数据是否存在当前年度的记录
                PreMuImportTongji preMuImportTongjiCondition = new PreMuImportTongji();
                preMuImportTongjiCondition.setUscc(uscc);
                preMuImportTongjiCondition.setYear(year);
                List<PreMuImportTongji> preMuImportTongjis = preMuImportTongjiService.selectPreMuImportTongjiList(preMuImportTongjiCondition);
                if (preMuImportTongjis != null && preMuImportTongjis.size() == 0) {
                    // 插入一条新数据
                    PreMuImportTongji preMuImportTongji = new PreMuImportTongji();
                    preMuImportTongji.setId(IdUtil.simpleUUID());
                    preMuImportTongji.setYear(year);
                    preMuImportTongji.setUscc(uscc);
                    preMuImportTongji.setCompanyName(dataSubmission.getCompanyName());
                    PreMuCompanyInfo preMuCompanyInfo = preMuCompanyInfoService.selectPreMuCompanyInfoByUscc(uscc);
                    preMuImportTongji.setCompanyProp(preMuCompanyInfo.getCompanyProp());
                    preMuImportTongji.setCompanyType(dataSubmission.getCompanyType());
                    preMuImportTongji.setCompanyScale(preMuCompanyInfo.getCompanyScale());
                    preMuImportTongji.setIndustryType(preMuCompanyInfo.getIndustryType());
                    preMuImportTongji.setAddr(preMuCompanyInfo.getDetailAddr());
                    preMuImportTongji.setTotalUsed(dataSubmission.getTotalUsed());
                    preMuImportTongji.setIndustryOutput(String.valueOf(dataSubmission.getIndustryOutput()));
                    preMuImportTongji.setCreateBy(submissionUpdateBy);
                    preMuImportTongji.setCreateDate(dataSubmission.getUpdateDate());
                    preMuImportTongji.setUpdateBy(submissionUpdateBy);
                    preMuImportTongji.setUpdateDate(dataSubmission.getUpdateDate());
                    preMuImportTongjiService.insertPreMuImportTongji(preMuImportTongji);
                }

                // 查询生态环境局导入数据是否存在当前年度的记录
                PreMuImportHuanbao preMuImportHuanbaoCondition = new PreMuImportHuanbao();
                preMuImportHuanbaoCondition.setUscc(uscc);
                preMuImportHuanbaoCondition.setYear(year);
                List<PreMuImportHuanbao> preMuImportHuanbaos = preMuImportHuanbaoService.selectPreMuImportHuanbaoList(preMuImportHuanbaoCondition);
                if (preMuImportHuanbaos != null && preMuImportHuanbaos.size() == 0) {
                    // 插入一条新数据
                    PreMuImportHuanbao preMuImportHuanbao = new PreMuImportHuanbao();
                    preMuImportHuanbao.setId(IdUtil.simpleUUID());
                    preMuImportHuanbao.setYear(year);
                    preMuImportHuanbao.setUscc(uscc);
                    preMuImportHuanbao.setCompanyName(dataSubmission.getCompanyName());
                    preMuImportHuanbao.setTotalEquivalent(dataSubmission.getTotalEquivalent());
                    preMuImportHuanbao.setCreateBy(submissionUpdateBy);
                    preMuImportHuanbao.setCreateDate(dataSubmission.getUpdateDate());
                    preMuImportHuanbao.setUpdateBy(submissionUpdateBy);
                    preMuImportHuanbao.setUpdateDate(dataSubmission.getUpdateDate());
                    preMuImportHuanbao.setCompanyType(dataSubmission.getCompanyType());
                    preMuImportHuanbaoService.insertPreMuImportHuanbao(preMuImportHuanbao);
                }

                // 查询人力资源和社会保障局导入数据是否存在当前年度的记录
                PreMuImportRenshe preMuImportRensheCondition = new PreMuImportRenshe();
                preMuImportRensheCondition.setUscc(uscc);
                preMuImportRensheCondition.setYear(year);
                List<PreMuImportRenshe> preMuImportRenshes = preMuImportRensheService.selectPreMuImportRensheList(preMuImportRensheCondition);
                if (preMuImportRenshes != null && preMuImportRenshes.size() == 0) {
                    // 插入一条新数据
                    PreMuImportRenshe preMuImportRenshe = new PreMuImportRenshe();
                    preMuImportRenshe.setId(IdUtil.simpleUUID());
                    preMuImportRenshe.setYear(year);
                    preMuImportRenshe.setUscc(uscc);
                    preMuImportRenshe.setCompanyName(dataSubmission.getCompanyName());
                    preMuImportRenshe.setAnnualEmployees(dataSubmission.getAnnualEmployees());
                    preMuImportRenshe.setCreateBy(submissionUpdateBy);
                    preMuImportRenshe.setCreateDate(dataSubmission.getUpdateDate());
                    preMuImportRenshe.setUpdateBy(submissionUpdateBy);
                    preMuImportRenshe.setUpdateDate(dataSubmission.getUpdateDate());
                    preMuImportRenshe.setCompanyType(dataSubmission.getCompanyType());
                    preMuImportRensheService.insertPreMuImportRenshe(preMuImportRenshe);
                }

                // 往涉企数据管理中添加数据
                String province = dataSubmission.getProvince();
                String city = dataSubmission.getCity();
                String county = dataSubmission.getCounty();
                PreMuImportLog preMuImportLog = new PreMuImportLog();
                preMuImportLog.setYear(dataSubmission.getYear());
                preMuImportLog.setProvince(province);
                preMuImportLog.setCity(city);
                preMuImportLog.setCounty(county);
                preMuImportLog.setUploadDate(new Date());
                preMuImportLog.setCreateBy(submissionUpdateBy);
                preMuImportLog.setCreateDate(new Date());
                preMuImportLog.setUpdateBy(submissionUpdateBy);
                preMuImportLog.setUpdateDate(new Date());
                preMuImportLog.setDeptCodeSum(1L);
                if (StrUtil.equals(dataSubmission.getCompanyType(), "1")) {
                    // 规上
                    // 税务局
                    preMuImportLog.setDeptCode("04");
                    preMuImportLogService.insertOrUpdateLog(preMuImportLog);
                    // 统计局
                    preMuImportLog.setDeptCode("01");
                    preMuImportLogService.insertOrUpdateLog(preMuImportLog);
                    // 生态环境局
                    preMuImportLog.setDeptCode("02");
                    preMuImportLogService.insertOrUpdateLog(preMuImportLog);
                    // 人社局
                    preMuImportLog.setDeptCode("05");
                    preMuImportLogService.insertOrUpdateLog(preMuImportLog);
                } else if (StrUtil.equals(dataSubmission.getCompanyType(), "2")) {
                    // 规下
                    // 税务局
                    preMuImportLog.setDeptCode("09");
                    preMuImportLogService.insertOrUpdateLog(preMuImportLog);
                    // 统计局
                    preMuImportLog.setDeptCode("06");
                    preMuImportLogService.insertOrUpdateLog(preMuImportLog);
                }
            }
            dto.setLatestApprovalDate(new Date());
            dto.setApprover(userId);
        }
        preMuEvaluationDataSubmissionMapper.updateDataByIds(dto);
        return AjaxResult.success();
    }
}
